package rpc.frame.client.proxy;

import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import rpc.frame.client.request.RpcRequestManager;
import rpc.frame.core.data.RpcRequest;
import rpc.frame.core.data.RpcResponse;
import rpc.frame.core.spring.SpringBeanFactory;
import rpc.frame.core.util.RequestIdUtil;

import java.lang.reflect.Method;

@Component
@Slf4j
public class CglibProxyCallBackHandler  implements MethodInterceptor {

    /**
     * 开始动态代理 生成网络通信的具体内容
     * 1.object 的方法放过不进行代理
     * 2.构建网络通信
     * 3.构建PRC请求
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        //判断是否是基类Object 的方法 比如 toString
        if(ReflectionUtils.isObjectMethod(method)){
            return method.invoke(this,objects);
        }

        //走网络调用
        //构建RPC
        RpcRequest request=RpcRequest.builder()
                .requestId(RequestIdUtil.requestId())
                .className(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .parameters(objects)
                .build();
        RpcRequestManager requestManager = SpringBeanFactory.getBean(RpcRequestManager.class);
        if(requestManager==null){
            throw new RuntimeException("没有RpcRequestManager");
        }
        RpcResponse rpcResponse = requestManager.sendRequest(request);
        if(rpcResponse.isError()){
            throw new RuntimeException("远程服务发生异常："+rpcResponse.getCause());
        }
        return rpcResponse.getResult();
    }

}
